<template>
  <div class="permissions-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>加载权限数据中...</span>
    </div>

    <!-- 权限列表 -->
    <div v-else class="permissions-list" ref="permissionsList">
      <!-- 全选 -->
      <div class="permission-item select-all">
        <el-checkbox v-model="selectAll" @change="handleSelectAll" :indeterminate="isIndeterminate">
          全选
        </el-checkbox>
      </div>

      <!-- 权限项 -->
      <div
        v-for="category in permissionsData"
        :key="category.id"
        class="permission-category"
        :class="{ highlighted: category.highlighted }"
      >
        <!-- 主分类 -->
        <div class="permission-item main-category" @click="toggleCategory(category.id)">
          <div class="category-header">
            <el-checkbox
              v-model="category.checked"
              @change="handleCategoryChange(category)"
              :indeterminate="getCategoryIndeterminate(category)"
              @click.stop
            >
              {{ category.name }}
            </el-checkbox>
            <div class="expand-icon" :class="{ expanded: category.expanded }">
              <el-icon><ArrowDown /></el-icon>
            </div>
          </div>
        </div>
        <!-- 操作权限 -->
        <div class="actions-container" v-show="category.expanded">
          <div
            v-for="action in category.children"
            :key="action.id"
            class="action-item"
            :class="{ highlighted: action.highlighted }"
          >
            <el-checkbox v-model="action.checked" @change="handleActionChange(category, action)">
              {{ action.name }}
            </el-checkbox>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowDown, Loading } from '@element-plus/icons-vue'

// 响应式变量
const loading = ref(false)

// 权限数据
const permissionsData = reactive([])

// API 调用函数
const fetchPermissionsData = async () => {
  try {
    loading.value = true
    const response = await fetch('http://localhost:9090/menuitems/get', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        // 如果需要认证，添加相应的 headers
        // 'Authorization': `Bearer ${token}`
      },
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()

    if (result.code === 200) {
      // 转换后端数据格式为前端需要的格式
      const convertedData = convertBackendDataToFrontend(result.data)
      // 清空原有数据并添加新数据
      permissionsData.splice(0, permissionsData.length, ...convertedData)
    } else {
      ElMessage.error(result.message || '获取权限数据失败')
    }
  } catch (error) {
    console.error('获取权限数据失败:', error)
    ElMessage.error('获取权限数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 数据转换函数：将后端数据转换为前端需要的格式
const convertBackendDataToFrontend = (backendData) => {
  return backendData.map((menu) => ({
    id: menu.strmenucode,
    name: menu.strmenuname,
    checked: false,
    expanded: true, // 默认展开
    children: menu.children
      ? menu.children.map((button) => ({
          id: button.strbuttoncode,
          name: button.strbuttonname,
          checked: false,
        }))
      : [],
  }))
}

// 获取所有可选择的项目（主分类 + 操作权限）
const getAllItems = () => {
  const items = []
  permissionsData.forEach((category) => {
    items.push(category) // 添加主分类
    if (category.children) {
      category.children.forEach((action) => {
        items.push(action) // 添加操作权限
      })
    }
  })
  return items
}

// 全选状态
const selectAll = computed({
  get() {
    const allItems = getAllItems()
    return allItems.length > 0 && allItems.every((item) => item.checked)
  },
  set() {
    // 通过 handleSelectAll 处理
  },
})

// 半选状态
const isIndeterminate = computed(() => {
  const allItems = getAllItems()
  const checkedCount = allItems.filter((item) => item.checked).length
  return checkedCount > 0 && checkedCount < allItems.length
})

// 计算主分类的半选状态
const getCategoryIndeterminate = (category) => {
  if (!category.children || category.children.length === 0) {
    return false
  }

  const checkedCount = category.children.filter((action) => action.checked).length
  return checkedCount > 0 && checkedCount < category.children.length
}

// 切换分类展开/收缩
const toggleCategory = (categoryId) => {
  const category = permissionsData.find((cat) => cat.id === categoryId)
  if (category) {
    category.expanded = !category.expanded
  }
}

// 全选/取消全选
const handleSelectAll = (checked) => {
  const allItems = getAllItems()
  allItems.forEach((item) => {
    item.checked = checked
  })
}

// 主分类变化时，影响所有操作权限
const handleCategoryChange = (category) => {
  if (category.children) {
    category.children.forEach((action) => {
      action.checked = category.checked
    })
  }
}

// 操作权限变化时，更新主分类状态
const handleActionChange = (category, action) => {
  // 检查主分类下所有操作权限的选中状态
  if (category.children) {
    const allChecked = category.children.every((action) => action.checked)
    const someChecked = category.children.some((action) => action.checked)

    if (allChecked) {
      category.checked = true // 全部选中
    } else if (someChecked) {
      category.checked = false // 部分选中（半选状态）
    } else {
      category.checked = false // 全部未选中
    }
  }
}

// 获取选中的权限数据（供父组件使用）
const getSelectedPermissions = () => {
  const selected = {
    categories: [],
    actions: [],
  }

  permissionsData.forEach((category) => {
    if (category.checked) {
      selected.categories.push({
        id: category.id,
        name: category.name,
      })
    }

    if (category.children) {
      category.children.forEach((action) => {
        if (action.checked) {
          selected.actions.push({
            id: action.id,
            name: action.name,
            categoryId: category.id,
            categoryName: category.name,
          })
        }
      })
    }
  })

  return selected
}

// 暴露方法给父组件
defineExpose({
  getSelectedPermissions,
  fetchPermissionsData,
})

// 组件挂载时获取权限数据
onMounted(() => {
  fetchPermissionsData()
})
</script>

<style>
@import '../views/login/index.css';
</style>
